I have a 3rd party ad script that I inject into my nuxt component using postscribe. The website works fine. However if I try to navigate away from the page without letting the script to finish loading. I get hit with the error loop below (in the browser console). The error show every millisecond and it doesn't go away unless I refresh the page.
invoke.js:1 Uncaught TypeError: Cannot read properties of null (reading 'document')
This is the code that I inject using postscribe
this.$postscribe('#myDivId', `
<script type="text/javascript">
atOptions = {
'key' : 'fiajiewfoj3jiosfo',
'format' : 'iframe',
'height' : 90,
'width' : 728,
'params' : {}
};
document.write('<scr' + 'ipt type="text/javascript" src="http' + (location.protocol === 'https:' ? 's' : '') + '://script-src.com/12345767890/invoke.js"></scr' + 'ipt>');
<\/script>`
);
I did try injecting it using vanilla javascript but that did not work as well.
let a= document.getElementById("myDiv")
let basePath = document.createElement('script')
basePath.type = "text/javascript"
basePath.setAttribute('async', 'true');
basePath.innerHTML = `<script type="text/javascript">
atOptions = {
'key' : 'fiajiewfoj3jiosfo',
'format' : 'iframe',
'height' : 90,
'width' : 728,
'params' : {}
};
document.write('<scr' + 'ipt type="text/javascript" src="http' + (location.protocol === 'https:' ? 's' : '') + '://script-src.com/12345767890/invoke.js"></scr' + 'ipt>');
<\/script>`
a.appendChild(basePath)
It also isn't fixed, if I'm running it with if (process.client) i.e.
if(process.client){this.$postscribe.......}
I suspect it has something to do with document.write() but I have no experience with document.write() and its behaviour.
Note: I didn't put in into the head() because I want this to appear in a particular div / component.